#!/bin/bash
TMPDIR="/tmp"

unpack_package() {
    DEBPATH="$1"
    ABS_DEBPATH="$(realpath "$DEBPATH")"
    OUTPATH=$(dirname "$DEBPATH")
    ABS_OUTPATH="$(realpath "$OUTPATH")"
    local fields=$(LC_ALL=C dpkg -f "$DEBPATH" 2>&1)

    if [[ "$(echo "$fields" | wc -l)" == 1 ]] && [[ "$fields" =~ "tar.zst" ]]; then
        local tempd=$(mktemp -d)
        [[ ! -d "$tempd" ]] && exit -1
        pushd "$tempd"
        ar x "$ABS_DEBPATH" control.tar.zst
        ar x "$ABS_DEBPATH" data.tar.zst
        mkdir DEBIAN
        [ -f control.tar.zst ] && tar --use-compress-program=unzstd -xvf control.tar.zst -C DEBIAN
        local package_name="$(grep Package DEBIAN/control | sed 's/^Package: //g')"
        mkdir -p "$ABS_OUTPATH/$package_name/"
        mv DEBIAN "$ABS_OUTPATH/$package_name/"
        mv data.tar.zst "$ABS_OUTPATH/$package_name"
        popd

        rm -rf "$tempd"

        pushd "$OUTPATH/$package_name/"
        [[ -f data.tar.zst ]] && tar --use-compress-program=unzstd -xvf data.tar.zst
        rm -f data.tar.zst
        popd
    else
        package_name=$(dpkg-deb -f "$DEBPATH" Package)
        mkdir -p "$OUTPATH/$package_name/DEBIAN/"

        dpkg -e "$DEBPATH" "$OUTPATH/$package_name/DEBIAN/"
        dpkg -X "$DEBPATH" "$OUTPATH/$package_name/"
    fi

    notify-send "$package_name 解包已完成" -i /usr/share/icons/uos-packaging-tools.png

    echo "---------------------------------------------------------------------------"
}

for arg in "$@"; do

    arg="${arg#file://}"

    unpack_package "$arg"
done

